package com.jffccloud.common.util;

import com.jffccloud.common.config.JffccloudProperties;
import com.jffccloud.common.constants.GlobalConstant;
import com.jffccloud.common.redis.IJedisClient;
import com.jffccloud.common.redis.JedisClientCluster;
import com.jffccloud.common.redis.JedisClientPool;
import com.jffccloud.common.util.SpringContextHolder;

import java.util.Map;

public class JedisUtil {
    private static JffccloudProperties getJffccloudProperties(){
        return SpringContextHolder.getBean(JffccloudProperties.class);
    }

    private static IJedisClient getJedisClient(){
        JffccloudProperties jffccloudProperties = getJffccloudProperties();
        if(jffccloudProperties.getRedis()==null||jffccloudProperties.getRedis().equals(GlobalConstant.REDIS_MODE_POOL)){
            return SpringContextHolder.getBean(JedisClientPool.class);
        }else{
            return SpringContextHolder.getBean(JedisClientCluster.class);
        }
    }

    public static void set(Object key, Object value){
        getJedisClient().set(key, value);
    }

    // 给某个key设值
    public static void set(Object key, Object value, int expireTime){
        getJedisClient().set(key, value, expireTime);
    }

    // 根据key获取value
    public static Object get(Object key){
        return getJedisClient().get(key);
    }

    // 根据键值获取value
    public static Object hashGet(Object key, String field){
        return getJedisClient().hashGet(key, field);
    }

    public static void hashSet(Object key, String field, Object value){
        getJedisClient().hashSet(key, field, value);
    }

    public static Map<String, Object> hashAllGet(Object key){
        return getJedisClient().hashAllGet(key);
    }

    // 判断key是否存在
    public static boolean existKey(Object key){
        return getJedisClient().existKey(key);
    }

    // 删除
    public static void delKey(Object key){
        getJedisClient().delKey(key);
    }

    /**
     * 加分布式锁
     *
     * @param lockKey
     * @param lockValue
     * @param expireTime
     * @return
     */
    public static boolean tryGetDistributedLock(String lockKey, String lockValue, int expireTime){
        return getJedisClient().tryGetDistributedLock(lockKey, lockValue, expireTime);
    }

    /**
     * 解分布式锁
     *
     * @param lockKey
     * @param lockValue
     * @return
     */
    public static boolean releaseDistributedLock(String lockKey, String lockValue){
        return getJedisClient().releaseDistributedLock(lockKey, lockValue);
    }
}
